import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    RefreshControl,
    ActivityIndicator,
    Image
} from 'react-native';
import { PullView } from 'react-native-pull';
import {
    Container,
    Content,
    Left,
    Thumbnail,
    Text,
    Body,
    Icon,
    List,
    ListItem,
    Spinner
} from 'native-base';
import Collapsible from 'react-native-collapsible';
import STRING from '../../const_string_zh_CN';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import course from '../../net/course.js';
import URL from '../../net/url.js';
import CourseInfo from '../../db/coursedb/study_course_table.js';

class study_course extends Component {
    static navigationOptions = ({ screenProps }) => ({
        tabBarLabel: screenProps.role == 'student' ? STRING.class_tab_study_name : STRING.class_tab_teach_name,
    });

    constructor(props) {
        super(props);
        //state内部维护的一个状态，我们刚开始进来的为空，来加载空的view
        this.state = {
            selectedItem: -1,
            course: null,
            refreshing: false

        };
        this.onPullRelease = this.onPullRelease.bind(this);
        this.topIndicatorRender = this.topIndicatorRender.bind(this);
    }

    async onPullRelease(resolve) {
        //do something
        setTimeout(() => {
            const { login_info } = this.props;
            let cs = new course();
            let outArray = cs.get_course(login_info.userName);
            outArray.then((rs) => {
                console.log('gggggggggg');
                console.log(rs);
                this.setState({ course: rs });

            });
            resolve();
        }, 3000);
    }

    topIndicatorRender(pulling, pullok, pullrelease) {

        const hide = { position: 'absolute', left: 10000 };
        const show = { position: 'relative', left: 0 };
        setTimeout(() => {
            if (pulling) {
                this.txtPulling && this.txtPulling.setNativeProps({ style: show });
                this.txtPullok && this.txtPullok.setNativeProps({ style: hide });
                this.txtPullrelease && this.txtPullrelease.setNativeProps({ style: hide });
            } else if (pullok) {
                this.txtPulling && this.txtPulling.setNativeProps({ style: hide });
                this.txtPullok && this.txtPullok.setNativeProps({ style: show });
                this.txtPullrelease && this.txtPullrelease.setNativeProps({ style: hide });
            } else if (pullrelease) {
                this.txtPulling && this.txtPulling.setNativeProps({ style: hide });
                this.txtPullok && this.txtPullok.setNativeProps({ style: hide });
                this.txtPullrelease && this.txtPullrelease.setNativeProps({ style: show });
            }
        }, 1);
        return (
            <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 60 }}>
                <ActivityIndicator size="small" color="gray" />
                <Text ref={(c) => { this.txtPulling = c; }}>下拉刷新...</Text>
                <Text ref={(c) => { this.txtPullok = c; }}>松开刷新...</Text>
                <Text ref={(c) => { this.txtPullrelease = c; }}>努力刷新中...</Text>
            </View>
        );
    }
    //rn的生命周期，初始化的时候会执行
    ////courseid, courseTitle, cheifTeachername, termcode, userid
    async componentWillMount() {
        const { login_info } = this.props;
        let courseIn = new CourseInfo();
        try {
            await courseIn.createCourseInfoTable();
            let info = await courseIn.queryCourseInfo(login_info.userName);
            if (info != null && info.length > 0) {
                console.log('courseIn1111111111');
                let outArray = JSON.parse(info.item(0).value);
                console.log(outArray);
                this.setState({ course: outArray });


            } else {
                console.log('courseIn2222222222');
                let cs = new course();
                let outArray = await cs.get_course(login_info.userName);
                this.setState({ course: outArray });
                await courseIn.insertCourseInfo(login_info.userName, JSON.stringify(outArray));
                await courseIn.closeCourseInfo();
            }
        } catch (e) {
            console.log("error", e);
        }
    }

    render() {
        if (!this.state.course) {
            return this.renderLoadingView();
        }
        /* scrollEnabled={true} */
        return (

            <Content scrollEnabled={true} style={StyleSheet.flatten(styles.Container)}>
                <Container>
                    <PullView
                        onPullRelease={this.onPullRelease}
                        topIndicatorRender={this.topIndicatorRender}
                        topIndicatorHeight={60}>
                        {this.renderContent(this.state.course)}
                    </PullView>
                </Container>
            </Content>

        );
    }
    //加载等待的view
    renderLoadingView() {
        return (
            <Container>
                <Content>
                    <Spinner color='green' />
                </Content>
            </Container>
        );
    }
    //将接口数据呈现在list组件上
    renderContent(l) {
        const { setCourseInfo } = this.props;
        if (l === undefined) {
            return (
                <Text>暂无课程！</Text>
            );
        }
        return l.map((v, i) => {
            return (
                <View key={i}>
                    <ListItem onPress={() => { this.setState(this.state.selectedItem != i ? { selectedItem: i } : { selectedItem: -1 }) }}
                        style={StyleSheet.flatten(styles.mainList)}>
                        <Text style={StyleSheet.flatten(styles.textStyle)}>{v.termname}</Text>
                    </ListItem>

                    <Collapsible collapsed={this.state.selectedItem === i ? false : true}>
                        <List>
                            {v.courseList.map((v, j) => {
                                return (
                                    <ListItem key={j} onPress={() => {
                                        setCourseInfo({
                                            type: 'GetCourseIdSuccess',
                                            payload: {
                                                courseid: v.id,
                                                chiefTeacherName: v.chiefTeacherName,
                                                coursetitle: v.title
                                            }
                                        });
                                        this.props.screenProps.parentNavigation.navigate('CourseInfo', { title: v.title });

                                    }}
                                        style={StyleSheet.flatten(styles.subList)}>
                                        <Thumbnail square source={require('../../images/course.png')}
                                            style={StyleSheet.flatten(styles.courseIcon)} />
                                        <Body>
                                            <Text style={StyleSheet.flatten(styles.subtextStyle)}>{v.title}</Text>
                                            {/* <Text note>李***</Text> */}
                                            <Text note>{v.chiefTeacherName}</Text>
                                        </Body>
                                        {/* <Image style={StyleSheet.flatten(styles.backIcon)} source={require('../../images/back.png')} /> */}
                                        {/* <Icon name="arrow-forward" style={{ opacity: 0.6 }} /> */}
                                    </ListItem>
                                );
                            })}
                        </List>
                    </Collapsible>
                </View>
            );
        })
    }

}
//组件样式控制
const styles = StyleSheet.create({
    mainList: {
        height: 40,
        marginRight: 0,
        marginLeft: 0,
        // marginTop: 1,
        // paddingBottom: 10,
        paddingLeft: 20,
        paddingRight: 20,
        backgroundColor: 'white',
        borderBottomWidth: 0.2,
        borderBottomColor: "#cac0c0",

    },
    subList: {
        height: 50,
        marginRight: 0,
        marginLeft: 0,
        paddingBottom: 10,
        paddingLeft: 20,
        paddingRight: 20,
        backgroundColor: 'white',
        borderBottomWidth: 0.3,
        borderBottomColor: "#cac0c0",
    },
    courseIcon: {
        width: 37,
        height: 37
    },
    textStyle: {
        fontSize: 17,
        color: '#353535',
    },
    subtextStyle: {
        fontSize: 15,
        color: '#353535',
    },
    Container: {
        marginTop: 15,
    },
    backIcon: {
        width: 20,
        height: 20,
        // marginLeft:'63%',
        marginRight: '5%'
    },
});
function mapStateToProps(state) {
    return { login_info: state.login.login_info }
}

function mapDispatchToProps(dispatch) {
    return {
        setCourseInfo: (state) => dispatch(state)
    }
}

const PageCourse = connect(
    mapStateToProps,
    mapDispatchToProps
)(study_course)
export default PageCourse;
